package com.yl.nettylearning.netty.day09;

import com.yl.nettylearning.netty.day08.StudentPOJO;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;

/**
 * @author yangl
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            System.out.println("客户端socketChannel的hashcode：" + ch.hashCode());
                            //加入protobuf的解码器，需要指定对哪种对象进行解码
                            ch.pipeline().addLast("decoder", new ProtobufDecoder(StudentInfo.MyMessage.getDefaultInstance()));
                            //可以使用一个集合管理socketChannel，在推送消息时，可以将业务加入到各个
                            // channel 对应的NIOEventLoop 的taskQueue 或者scheduleTaskQueue
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });
            System.out.println("server is ready...");
            ChannelFuture channelFuture = bootstrap.bind(6666).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
